<template>
  <el-container class="activity-edit">
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="110px">
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="form.model.title" placeholder="例如：国庆活动" />
        </el-form-item>
        <el-form-item v-if="form.model.status == 'ing'" label="活动时间" required>
          <el-form-item prop="start_time">
            <el-date-picker
              v-model="form.model.start_time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              :disabled="activityStatus"
              prefix-icon="Calendar"
              placeholder="开始时间"
              :editable="false"
            />
          </el-form-item>
          <span class="sa-m-l-12 sa-m-r-12">至</span>
          <el-form-item prop="end_time">
            <el-date-picker
              v-model="form.model.end_time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              prefix-icon="Calendar"
              placeholder="结束时间"
              :editable="false"
              @change="onChangeEndtime"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item v-if="form.model.status != 'ing'" label="活动时间" prop="dateTime">
          <div>
            <el-date-picker
              v-model="form.model.dateTime"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              prefix-icon="Calendar"
              :editable="false"
            />
          </div>
        </el-form-item>
        <!-- 满额立减/满额折扣 -->
        <full-reduce-discount
          v-if="form.model.type == 'full_reduce' || form.model.type == 'full_discount'"
          :activityDetail="form"
        ></full-reduce-discount>
        <!-- 满赠 -->
        <full-gift v-if="form.model.type == 'full_gift'" :activityDetail="form"></full-gift>
        <!-- 满包邮 -->
        <free-shipping
          v-if="form.model.type == 'free_shipping'"
          :activityDetail="form"
        ></free-shipping>
        <!-- 普通拼团/阶梯拼团 -->
        <groupon
          v-if="form.model.type == 'groupon' || form.model.type == 'groupon_ladder'"
          :activityDetail="form"
          :activityStatus="activityStatus"
        ></groupon>
        <!-- 秒杀 -->
        <seckill
          v-if="form.model.type == 'seckill'"
          :activityDetail="form"
          :activityStatus="activityStatus"
        ></seckill>
        <signin
          v-if="form.model.type == 'signin'"
          :activityDetail="form"
          :activityStatus="activityStatus"
        />
        <el-form-item label="活动说明">
          <el-input
            class="richtext-title"
            v-model="form.model.richtext_title"
            placeholder="请选择活动说明"
          >
            <template #append>
              <el-button class="is-link" type="info" @click="selectRichtext"
                >选择活动说明</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <template v-if="form.model.type != 'signin'">
          <el-form-item class="sa-m-b-8" label="活动商品" prop="goodsType" v-if="!isActivity">
            <el-radio-group
              v-model="goodsType"
              :disabled="activityStatus"
              @change="changeGoodsType"
            >
              <el-radio label="all">全部商品</el-radio>
              <el-radio label="part">部分商品</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            :label="isActivity ? '活动商品' : ''"
            :prop="goodsType == 'part' || isActivity ? 'goods_list' : ''"
            v-if="goodsType == 'part'"
          >
            <div>
              <el-button
                class="is-link"
                type="primary"
                @click="selectGoods"
                :disabled="activityStatus"
                >+ 添加商品</el-button
              >
              <div
                class="sa-template-wrap sa-m-t-8"
                :class="isActivity ? 'sa-template-wrap-activity' : ''"
                v-if="form.model.goods_list.length > 0"
              >
                <div class="title sa-flex">
                  <div class="key">商品信息</div>
                  <div class="key setting" v-if="isActivity">设置</div>
                  <div class="oper">操作</div>
                </div>
                <div>
                  <div
                    class="item"
                    v-for="(element, index) in form.model.goods_list"
                    :key="element"
                  >
                    <el-form-item class="key">
                      <sa-image :url="element.image" size="40"></sa-image>
                      <div class="goods sa-m-l-12">
                        <div class="goods-title sa-m-b-6 sa-table-line-1">
                          {{ element.title }}
                        </div>
                        <div class="goods-price"> ¥{{ element.price.join('~') }} </div>
                      </div>
                    </el-form-item>
                    <el-form-item class="setting" v-if="isActivity">
                      <el-button
                        class="is-link"
                        type="primary"
                        @click="setActivitySkuPrices(index, element.id)"
                        >设置商品</el-button
                      >
                    </el-form-item>
                    <el-form-item class="oper">
                      <el-button
                        class="is-link"
                        type="danger"
                        @click="deleteGoods(index)"
                        :disabled="activityStatus"
                      >
                        移除
                      </el-button>
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </template>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.activity.activity.add'"
        type="primary"
        @click="confirm"
        >保存</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.activity.activity.edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { computed, onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../activity.service';
  import { useModal } from '@/sheep/hooks';
  import { getActivityForm, handleForm } from './data';
  import { cloneDeep } from 'lodash';

  import fullReduceDiscount from './components/full-reduce-discount.vue';
  import FullGift from './components/full-gift.vue';
  import FreeShipping from './components/free-shipping.vue';
  import Groupon from './components/groupon.vue';
  import Seckill from './components/seckill.vue';
  import Signin from './components/signin.vue';
  import RichtextSelect from '../../data/richtext/select.vue';
  import GoodsSelect from '../../goods/goods/select.vue';
  import ActivitySku from '../../activity/activity/sku.vue';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  const isActivity = computed(
    () =>
      props.modal.params.atype == 'groupon' ||
      props.modal.params.atype == 'groupon_ladder' ||
      props.modal.params.atype == 'seckill',
  );

  const activityStatus = ref(false);

  const formRef = ref();
  const form = reactive({
    model: getActivityForm(props.modal.params.atype).model,
    rules: getActivityForm(props.modal.params.atype).rules,
  });

  async function getDetail() {
    const { error, data } = await api.activity.detail(props.modal.params.id);
    if (error === 0) {
      form.model = data;

      // 处理时间
      form.model.dateTime = [form.model.start_time, form.model.end_time];

      // 处理商品
      if (form.model.goods_ids) {
        goodsType.value = 'part';
      }
      activityStatus.value = data.status == 'ing';
    }
  }

  const goodsType = ref('all');
  function changeGoodsType() {
    if (goodsType.value == 'all') {
      form.model.goods_ids = null;
      form.model.goods_list = [];
    } else if (goodsType.value == 'part') {
    }
  }

  function selectRichtext() {
    useModal(
      RichtextSelect,
      {
        title: '选择活动说明',
      },
      {
        confirm: (res) => {
          form.model.richtext_title = res.data.title;
          form.model.richtext_id = res.data.id;
        },
      },
    );
  }

  function selectGoods() {
    let ids = [];
    form.model.goods_list.forEach((i) => {
      ids.push(i.id);
    });
    useModal(
      GoodsSelect,
      {
        title: '选择商品',
        multiple: true,
        ids,
      },
      {
        confirm: (res) => {
          res.data.forEach((item) => {
            let findItem = form.model.goods_list.find((k) => k.id == item.id);
            if (findItem) {
              item.activity_sku_prices = findItem.activity_sku_prices;
            }
          });
          form.model.goods_list = res.data;
        },
      },
    );
  }
  function deleteGoods(index) {
    form.model.goods_list.splice(index, 1);
  }

  function setActivitySkuPrices(index, id) {
    useModal(
      ActivitySku,
      {
        title: '设置商品',
        model: form.model,
        goods_id: id,
        activityStatus: activityStatus.value,
      },
      {
        confirm: (res) => {
          form.model.goods_list[index].activity_sku_prices = res.data;
        },
      },
    );
  }

  function onChangeEndtime(val) {
    form.model.dateTime[1] = val
  }

  function confirm() {
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      let submitForm = handleForm(cloneDeep(form.model));
      if (submitForm) {
        const { error } =
          props.modal.params.type == 'add'
            ? await api.activity.add(submitForm)
            : await api.activity.edit(submitForm.id, submitForm);

        error == 0 && emit('modalCallBack', { event: 'confirm' });
      }
    });
  }

  onMounted(() => {
    if (props.modal.params.type == 'edit') {
      getDetail();
    }

    if (isActivity.value) {
      goodsType.value = 'part';
    }
  });
</script>
<style lang="scss" scoped>
  .activity-edit {
    :deep() {
      .label-inner {
        .el-form-item__label {
          font-size: 12px;
        }
      }
      .el-form-item-wrap {
        .el-form-item__label {
          font-size: 12px;
          width: fit-content !important;
        }

        .el-form-item--label-left {
          margin-bottom: 18px !important;
        }

        .desc {
          font-size: 12px;
        }
      }
      .sa-template-wrap {
        width: 360px;
        .title {
          margin: 0;
        }
        .setting {
          flex: none;
          width: 100px;
        }
        .oper {
          flex: none;
          width: 60px;
        }
        .item {
          border-bottom: 1px solid var(--sa-space);
          margin-top: 12px;
          & > .el-form-item {
            margin-bottom: 12px;
          }
          .goods {
            line-height: 16px;
            font-size: 12px;
            flex: 1;
            .goods-title {
              color: var(--sa-font);
            }
            .goods-price {
              color: var(--el-color-danger);
            }
            .goods-stock {
              color: var(--sa-font);
            }
          }
        }
        &.sa-template-wrap-activity {
          width: 464px;
        }
      }
    }
    .richtext-title {
      :deep() {
        .el-input-group__append {
          width: 106px;
        }
      }
    }
  }
</style>
